import { DEFAULT_PAGE, RouteView } from './config'


// 单独处理
function extract(str) {
	const regex = /\[(.*?)\]/g
	let matches
	const results = []
	while ((matches = regex.exec(str)) !== null) {
		results.push(matches[1])
	}
	return results
}

// 树转 object
function treeToObject(children) {
	const obj = {}
	for (let i = 0; i < children.length; i++) {
		const element = children[i]
		if (element.children && element.children.length) {
			const name = extract(element.l3).slice(1).join('-')
			obj[name] = extractFieldFromTree(element.children, 'name')
		} else {
			obj[element.l3] = null
		}
	}
	return obj
}

// 提取 tree 中的 对应字段合并为 一个 数组
function extractFieldFromTree(tree, field) {
	let result = []
	tree.forEach(node => {
		if (node[field] !== undefined) {
			result.push(node[field])
		}
		if (node.children && node.children.length > 0) {
			result = result.concat(extractFieldFromTree(node.children, field))
		}
	})
	return result
}

// 生成
export const generator = (routerMap, parent, level = 0) => {
	return routerMap.map(item => {
		const { title, show, hideChildren, hiddenHeaderContent, target, icon } = item || {}
		const currentRouter = {
			path: item.path || `${(parent && parent.path) || ''}/${item.key}`,
			name: item.name || item.key || '',
			// 一种是用户定义，一种是默认
			component: item.component ? () => import(`@/${DEFAULT_PAGE}/${item.component}.vue`) : RouteView,
			meta: {
				title: title,
				icon: icon || undefined,
				hiddenHeaderContent: hiddenHeaderContent,
				target,
				permission: {}
			}
		}
		if (show === false) {
			currentRouter.hidden = true
		}
		if (hideChildren) {
			currentRouter.hideChildrenInMenu = true
		}
		if (!currentRouter.path.startsWith('http')) {
			currentRouter.path = currentRouter.path.replace('//', '/')
		}
		item.redirect && (currentRouter.redirect = item.redirect)

		if (['home'].includes(item.name)) {
			currentRouter.meta.permission = extractFieldFromTree(item.children, 'name')
			item.children = undefined
		} else if (level === 1) {
			if (['fast', 'deploy', 'release'].includes(item.name)) {
				currentRouter.meta.permission = treeToObject(item.children)
			} else {
				currentRouter.meta.permission = extractFieldFromTree(item.children, 'name')
			}
			item.children = undefined
		}

		if (item.children && item.children.length > 0) {
			currentRouter.children = generator(item.children, currentRouter, level + 1)
		}
		return currentRouter
	})
}

// 列表转树
export const listToTree = (list, tree, parentId) => {
	list.forEach(item => {
		if (item.parentId === parentId) {
			const child = {
				...item,
				key: item.key || item.name,
				children: []
			}
			listToTree(list, child.children, item.id)
			if (child.children.length <= 0) {
				delete child.children
			}
			tree.push(child)
		}
	})
}
